"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const NodeCache = require("node-cache");
const weixin_request_1 = require("./weixin-request");
const mch_1 = require("./mch");
const common_1 = require("./common");
const errors_1 = require("./errors");
const sns_1 = require("./sns");
const myCache = new NodeCache();
class WeiXinSDK {
    constructor() {
        this.config = {};
        this.cr = new common_1.ConfigReader(this.config);
        this.mch = new mch_1.MCH(this.cr);
        this.sns = new sns_1.SNS(this.cr);
    }
    /**
     * 获取 token
     * @param appid 第三方用户唯一凭证
     * @param secret 第三方用户唯一凭证密钥，即appsecret
     * @param fromCache 是否从缓存读取,默认为 true
     */
    async token(fromCache) {
        let appid = this.cr.getAppId();
        let secret = this.cr.getAppKey();
        fromCache = fromCache == null ? true : fromCache;
        let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`;
        let r;
        if (fromCache) {
            r = myCache.get(appid);
        }
        if (r == null) {
            r = await weixin_request_1.WeiXinRequest.get(url);
            myCache.set(appid, r, r.expires_in);
        }
        return r;
    }
    async access_token(code) {
        if (!code)
            throw errors_1.errors.argumentNull("code");
        let appid = this.cr.getAppId();
        let secret = this.cr.getAppKey();
        let url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`;
        return weixin_request_1.WeiXinRequest.get(url);
    }
}
exports.WeiXinSDK = WeiXinSDK;
